package com.hnluchuan.bmjlearning.security;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy;

import com.hnluchuan.bmjlearning.common.UserType;
import com.hnluchuan.bmjlearning.model.User;

public class MyConcurrentSessionControlAuthenticationStrategy extends ConcurrentSessionControlAuthenticationStrategy  {

	private SessionRegistry sessionRegistry;
	
	public MyConcurrentSessionControlAuthenticationStrategy(SessionRegistry sessionRegistry) {
		super(sessionRegistry);
		this.sessionRegistry = sessionRegistry;
	}

	@Override
	public void onAuthentication(Authentication authentication, HttpServletRequest request,
			HttpServletResponse response) {
		sessionRegistry.registerNewSession(request.getSession().getId(), authentication.getPrincipal());
		
		User user = (User) authentication.getPrincipal();
		if (user.getType() != UserType.Clinic.getValue()) { // 只针对诊所用户
			return;
		}
		List<SessionInformation> sessionInformations = sessionRegistry.getAllSessions(authentication.getPrincipal(), false);
		for (SessionInformation si : sessionInformations) {
			if (si.getSessionId().equals(request.getSession().getId())) {
				continue;
			}
			si.expireNow();
		}
		
	}
}
